from datetime import datetime, timedelta
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings


router = APIRouter(prefix='/brand/domains', tags=['Brand'])
module_name = '品牌商模块 - 自定义域名'


@router.get('', response_model=schemas.BaseApiListOut)
async def get_domains(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    brand_id: Optional[int] = None,
    code: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        品牌商 自定义域名列表
    """

    objs = OemModel.TenantDomain.with_('brand')

    if brand_id:
        objs = objs.where('brand_id', brand_id)

    if code:
        objs = objs.where('code', code)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'domain', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('', response_model=schemas.BaseApiOut)
async def add_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: ApiSchemas.brand.TenantDomainCreate,
):
    """
        添加自定义域名
    """

    # 判断商户
    _exits = OemModel.Company.where('brand_id', post.brand_id).first()
    if not _exits:
        return schemas.BaseApiOut(code=1, message='商户不存在')
    # 判断域名是否存在
    _exits = OemModel.TenantDomain.where('domain', post.domain.lower()).first()
    if _exits:
        return schemas.BaseApiOut(code=1, message='域名已存在')

    try:
        obj = OemModel.TenantDomain.create(
            code=post.code.lower(),
            brand_id=post.brand_id,
            domain=post.domain,
            status=post.status,
            type=post.type,
            is_default=post.is_default,
            user_id=current_user.id,
        )
        print('操作成功:', obj.fresh().id)

        # 如果设置为默认域名，则将其他域名设置为非默认域名
        if post.is_default == 1:
            OemModel.TenantDomain.where(
                'id', '!=', obj.fresh().id
            ).where('brand_id', post.brand_id).where('is_default', 1).update({'is_default': 0})
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.post('/ssl/{id}', response_model=schemas.BaseApiOut)
async def ssl_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    data: dict = Body(),
):
    """
        ssl 自定义域名
    """

    obj = OemModel.TenantDomain.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此域名不存在')

    try:
        obj.ssl_pem = data['ssl_pem']
        obj.ssl_key = data['ssl_key']
        obj.ssl_expire = data['ssl_expire']

        if obj.deploy_ssl_status == 1:
            # 重置为末部署
            obj.deploy_ssl_status = 0

        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.post('/ssldeploy/{id}', response_model=schemas.BaseApiOut)
async def ssl_deploy_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    data: dict = Body(),
):
    """
        更新 ssl 部署状态
    """

    obj = OemModel.TenantDomain.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此域名不存在')

    try:
        obj.deploy_status = data['deploy_status']
        obj.deploy_ssl_status = data['deploy_ssl_status']
        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.post('/template/{id}', response_model=schemas.BaseApiOut)
async def template_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    data: dict = Body(),
):
    """
        更新模板内容
    """

    obj = OemModel.TenantDomain.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此域名不存在')

    try:
        obj.h5_template = data['h5_template']
        obj.pc_template = data['pc_template']
        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.post('/tenant/{code}', response_model=schemas.BaseApiOut)
async def tenant_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    code: str,
):
    """
        返回商户自定义域名
    """

    obj = OemModel.TenantDomain.where('is_default', 1).where('code', code).first()
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此域名不存在')

    return {'data': {'tenant_domain': obj.domain}}


@router.delete('/delete-batch', response_model=schemas.BaseApiOut)
async def delete_batch_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    data: dict = Body(),
):
    """
        批量删除自定义域名
    """

    delete_obj = []

    for id in data['ids']:
        # 商品信息
        obj = OemModel.TenantDomain.find(id)
        if obj is None:
            return schemas.BaseApiOut(code=1, message='此域名不存在')

        delete_obj.append(obj)

    try:
        for obj in delete_obj:
            obj.delete()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.put('/{id}', response_model=schemas.BaseApiOut)
async def edit_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: ApiSchemas.brand.TenantDomainCreate,
    id: int,
):
    """
        编辑自定义域名
    """

    obj = OemModel.TenantDomain.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此自定义域名不存在')

    post.domain = post.domain.lower()
    # 判断域名是否存在
    _exits = OemModel.TenantDomain.where('domain', post.domain).where('id', '!=', id).first()
    if _exits:
        return schemas.BaseApiOut(code=1, message='域名已存在')

    try:
        obj.is_default = post.is_default
        obj.domain = post.domain
        obj.type = post.type
        obj.status = post.status
        obj.save()

        if post.is_default == 1:
            OemModel.TenantDomain.where(
                'id', '!=', obj.id
            ).where('brand_id', post.brand_id).where('is_default', 1).update({'is_default': 0})

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.delete('/{id}', response_model=schemas.BaseApiOut)
async def delete_domain(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        删除自定义域名
    """

    obj = OemModel.TenantDomain.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        obj.delete()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}
